<template>
    <div class="home">
        <div>
            <input
                    type="text"
                    v-model="keyword"
                    placeholder="tablename or fieldsName"
                    @enter.stop="() => search()"
            />
            <button @click="() => search()">搜索</button>
        </div>

        <div style="display: flex">
            <div style="padding-right: 10px">
                <ul>
                    <li v-for="table in resultList" :key="table && table.tableName">
                        <div
                                :draggable="true"
                                @dragstart="dragStart($event, table)"
                                @dragend="dragEnd($event, table)"
                        >
                            <span class="needHighLignt"> {{ table.tableName }}</span>
                            <span style="padding-left: 10px" @click="() => go2Table(table)"
                            >查看数据</span>
                            <i class="iconfont " :class="[table.isOpen?'icon-UP-':'icon-downpx']"
                               style="padding-left:10px;"
                               @click.stop="()=>{table.isOpen=!table.isOpen;$forceUpdate()}"></i>
                        </div>
                        <ul v-show="table.isOpen">
                            <li v-for="field in table.fields" :key="field.name">
                                <div class="needHighLignt">{{ field.name }}</div>
                                <div style="padding-left: 10px" v-if="field.subField">
                                    {{ field.subField }}
                                </div>
                            </li>
                        </ul>
                    </li>
                </ul>
            </div>
            <!--  -->
            <div>
                <h1>绑定外键-放置区域</h1>
                <button @click="() => saveBindTable()">保存</button>
                <div
                        style="background: #f9f9f9; width: 600px; height: 100%;min-height: 600px;"
                        @drop.stop="drop"
                        @dragover.prevent
                >
                    <ul style="display: flex;flex-wrap:wrap;">
                        <li
                                v-for="(table,index) in dropList"
                                :key="table.id"
                                v-if="table.id"
                                style="padding-right: 20px;"
                        >
                            <div
                                    :draggable="true"
                                    @dragstart="dragStart($event, table)"
                                    @dragend="dragEnd($event, table)"
                            >
                <span>
                  {{ table.tableName }}
                  <span
                          @click="() => delDrop(table)"
                          style="cursor: pointer; padding-left: 20px"
                  >del</span
                  ></span
                >
                            </div>
                            <ul>
                                <li
                                        v-for="field in table.fields"
                                        :key="table.id+'_'+field.name"
                                        :draggable="true"
                                        @dragstart="() => {currentFieldDrag = { table, field };console.log('dragstart field',currentFieldDrag)}"
                                        @dragend="() => {setTimeout(()=>{currentFieldDrag = null;},300)}"
                                        @drop.stop="() => dropField(table.id,table, field, currentFieldDrag)"
                                        @dragover.prevent
                                >
                                    <div>{{ field.name }}</div>
                                    <!-- 渲染子字段 -->
                                    <div style="display: flex" v-if="field.subField">
                                        <span> {{ field.subField }}</span>
                                        <span
                                                style="padding-left: 10px"
                                                @click.stop="  () =>
                          delSubField(
                              table.id,
                            table.tableName,
                            field.name,
                            field.subField
                          )
                      "
                                        >del</span
                                        >
                                    </div>
                                    <!-- <div style="padding-left:10px;"
                                       v-if="field.subField&&field.subField.fieldName">{{field&&field.subField&&field.subField.tableName}}.{{field&&field.subField&&field.subField.fieldName}}</div> -->
                                </li>
                            </ul>
                        </li>
                    </ul>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
    import {createA, safeParseJson, uuid} from '../utils/utils'
    import myalert from "../utils/myalert";

    export default {
        name: "Home",
        data() {
            return {
                setTimeout: window.setTimeout,
                currentDragger: null,
                resultList: [],
                keyword: sessionStorage.getItem("createSearch") || "",
                dropList: [],
                currentFieldDrag: null,
                console: window.console
            };
        },
        components: {},
        mounted() {
            //已进入就触发搜索
            if (this.keyword) {
                this.search()
            }
        },
        methods: {
            drop() {
                var item = JSON.parse(JSON.stringify((this.currentDragger)))
                item.id = uuid()
                this.dropList.push(item);
                console.log("dropList", this.dropList);
            },
            dragStart(e, table) {
                this.currentDragger = table;
                console.log("dragEnter", e, table);
            },
            dragEnd(e, table) {
                this.currentDragger = null;
                console.log("dragEnd", e, table);
            },
            delDrop(tableItem) {
                var index = this.dropList.findIndex(
                    (item) => item.tableName == tableItem.tableName
                );
                if (index >= 0) {
                    this.dropList.splice(index, 1);
                }
            },
            dropField(tableId, masterTable, masterField, subFiledItem) {
                console.log("dropField tableId subFiledItem", tableId, subFiledItem)
                if (!subFiledItem) return false;
                var subField = {
                    // ...subFiledItem,
                    tableName: subFiledItem.table.tableName,
                    fieldName: subFiledItem.field.name,
                };

                //添加 字段的子字段
                var index = this.dropList.findIndex(
                    (table) => table.id == tableId
                );
                if (index >= 0) {
                    var index2 = this.dropList[index].fields.findIndex(
                        (item) => item.name == masterField.name
                    );
                    if (index2 >= 0) {
                        this.dropList[index].fields[index2].subField = subField;
                        this.$forceUpdate();
                    }
                }
            },
            delSubField(tableId, tableName, fieldName, subFiled) {
                var index = this.dropList.findIndex(
                    (table) => table.id == tableId
                );
                if (index >= 0) {
                    var index2 = this.dropList[index].fields.findIndex(
                        (item) => item.name == fieldName
                    );
                    if (index2 >= 0) {
                        this.dropList[index].fields[index2].subField = null;
                        delete this.dropList[index].fields[index2].subField;
                        this.$forceUpdate();
                    }
                }
                //删除绑定
                axios
                    .post(`/databases/delSubField`, {
                        masterTable: tableName,
                        masterfieldName: fieldName,
                        subTable: subFiled.tableName,
                        subfieldName: subFiled.fieldName,
                    })
            },
            search() {
                var self = this;
                var searchHistory = safeParseJson(sessionStorage.getItem("searchHistory")) || []
                //点击保存最新的搜索
                var createSearch = this.keyword
                sessionStorage.setItem("createSearch", createSearch)
                axios
                    .get(`/databases/search?keyword=${this.keyword}`)
                    .then((res) => res.data)
                    .then((res) => {
                        this.resultList = res;


                        self.$nextTick(() => {
                            $('body').unhighlight();
                            $('body .needHighLignt').highlight(self.keyword);
                        })


                    });
            },
            async saveBindTable() {
                var self = this;
                for (const index in this.dropList) {
                    for (const index2 in this.dropList[index].fields) {
                        if (self.dropList[index].fields[index2].subField) {
                            await axios
                                .post(`/databases/tableBind`, {
                                    masterTable: self.dropList[index].tableName,
                                    masterfieldName: self.dropList[index].fields[index2].name,
                                    subTable:
                                    self.dropList[index].fields[index2].subField.tableName,
                                    subfieldName:
                                    self.dropList[index].fields[index2].subField.fieldName,
                                })
                                .then((res) => res.data)
                                .then((res) => {
                                    if (res.code != 400) {
                                        myalert.success("绑定成功")
                                    }
                                });
                        }
                    }
                }
            },
            go2Table(table) {
                createA(`/showTable?table=${table.tableName}`, "_blank");
            },
        },
    };
</script>
<style>
    .highlight {
        background-color: #FFFF88;
    }
</style>